package com.chinacoal.hr.levelimpl.controller;

import com.chinacoal.hr.levelapi.client.response.Result;
import com.chinacoal.hr.levelapi.client.response.ResultGenerator;
import com.chinacoal.hr.levelapi.controller.FileServiceClient;
import com.chinacoal.hr.levelapi.entity.FileInfo;
import com.chinacoal.hr.levelimpl.service.FileInfoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: YunTao.Li
 * @create: 2019-12-04 19:09
 * @description:
 **/
@RestController
public class FileController implements FileServiceClient {

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileInfoService fileInfoService;

    @Override
    public Result testFile() {
        return ResultGenerator.genOkResult("31111111111111");
    }

    @GetMapping("/filees2")
    @ApiOperation(value = "测试url")
    public Result testFile2() {
        return ResultGenerator.genOkResult("2222222222222");
    }


    /**
     * @param file :
     * @return : com.chinacoal.hr.levelapi.response.Result
     * @author : YunTao.Li
     * @date : 2019/12/4 2019/12/4
     */
    @PostMapping("/file/upload")
    @ApiOperation(value = "文件上传")
    public Result singleFileUpload(MultipartFile file, String paDocId, String paType, String createdBy) {
        if (Objects.isNull(file) || file.isEmpty()) {
            String errorMsg = "文件为空，请重新上传";
            logger.error(errorMsg);
            return ResultGenerator.genFailedResult(errorMsg);
        }

        try {
            // step1 : 获得上传文件的信息
            String fileRealName = file.getOriginalFilename();
            String fileSuffixName = fileRealName.substring(fileRealName.lastIndexOf(".") + 1);
            String fileRandomName = RandomStringUtils.random(15, true, true) + "." + fileSuffixName;
            long fileSize = file.getSize();

            // step2 : 上传文件到指定目录
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FOLDER + fileRandomName);
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER));
            }
            //文件写入指定路径
            Files.write(path, bytes);

            // step3 : 记录文件信息到表中
            FileInfo record = new FileInfo();
            record.setFilePath(path.toString());
            record.setFileName(fileRandomName);
            record.setFileRealName(fileRealName);
            record.setFileSize(fileSize);
            record.setFileSuffixName(fileSuffixName);
            record.setPaDocId(paDocId);
            record.setPaType(paType);
            record.setCreatedBy(createdBy);
            this.fileInfoService.addFileInfo(record);

            return ResultGenerator.genOkResult();
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultGenerator.genFailedResult(e.getMessage());
        }
    }

    /**
     * 查询文件列表
     *
     * @param page    :
     * @param limit   :
     * @param paDocId :
     * @return : com.chinacoal.hr.levelimpl.response.Result
     * @author : YunTao.Li
     * @date : 2020/1/2 2020/1/2
     */
    @ResponseBody
    @GetMapping("/files")
    @ApiOperation(value = "查询文件列表")
    public Result fileList(@ApiParam("当前页数") long page,
                           @ApiParam("每页条数") long limit,
                           @ApiParam("业务ID") String paDocId) {

        if(StringUtils.isBlank(paDocId)) {
            return ResultGenerator.genOkResult();
        }

        // 构建查询条件
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("page", page);
        condition.put("limit", limit);
        condition.put("paDocId", paDocId);

        List<FileInfo> recordList = null;
        try {
            recordList = this.fileInfoService.getFileInfosWithOutPage(condition);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultGenerator.genFailedResult(e.getMessage());
        }
        return ResultGenerator.genOkResult(recordList);
    }

    /**
     * 文件下载
     *
     * @param request  :
     * @param response :
     * @param fileId   :
     * @return : void
     * @author : YunTao.Li
     * @date : 2020/1/2 2020/1/2
     */
    @RequestMapping(value = "/file/download", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "文件下载")
    public void download(HttpServletRequest request, HttpServletResponse response, String fileId) {
        OutputStream toClient = null;
        try {
            FileInfo file = this.fileInfoService.getFileInfo(fileId);
            String filePath = file.getFilePath();
            String fileName = file.getFileRealName();
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
//            response.reset();// 清空response
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
//            String outPutFileName = fileName;
//            outPutFileName = new String(fileName.getBytes("GB2312"), "UTF-8");
            System.out.println("filename :" + fileName);
//            response.setHeader("Content-Disposition", "attachment;filename=" + outPutFileName);// 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            toClient.write(buffer);
            toClient.flush();

        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                toClient.close();
            } catch (IOException e) {
                e.printStackTrace();
                toClient = null;
            }
        }
    }

    /**
     * 删除文件
     *
     * @param fileId :
     * @return : com.chinacoal.hr.levelimpl.response.Result
     * @author : YunTao.Li
     * @date : 2020/1/2 2020/1/2
     */
    @DeleteMapping("/file/{fileId}")
    @ApiOperation(value = "删除文件")
    public Result delete(@PathVariable String fileId) {
        Map<String, String> result = this.fileInfoService.deleteFileInfo(fileId);

        if ("-1".equals(result.get("code"))) {
            String message = result.get("message");
            return ResultGenerator.genFailedResult(message);
        } else {
            return ResultGenerator.genOkResult();
        }
    }
}
